#!/bin/bash

# Vue3 Antd Dynamic Form 发布脚本
# 使用方法: ./scripts/publish.sh [patch|minor|major]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否在正确的目录
if [ ! -f "package.json" ]; then
    print_error "请在项目根目录运行此脚本"
    exit 1
fi

# 获取版本类型参数
VERSION_TYPE=${1:-patch}

if [[ ! "$VERSION_TYPE" =~ ^(patch|minor|major)$ ]]; then
    print_error "版本类型必须是 patch、minor 或 major"
    exit 1
fi

print_message "开始发布流程..."

# 1. 检查是否有未提交的更改
if [ -n "$(git status --porcelain)" ]; then
    print_warning "检测到未提交的更改，请先提交或暂存更改"
    git status
    read -p "是否继续？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# 2. 安装依赖
print_message "安装依赖..."
yarn install

# 3. 代码质量检查
print_message "运行代码质量检查..."
yarn lint || {
    print_error "代码检查失败，请修复问题后重试"
    exit 1
}

# 4. 类型检查
print_message "运行类型检查..."
yarn type-check || {
    print_error "类型检查失败，请修复问题后重试"
    exit 1
}

# 5. 构建
print_message "构建项目..."
yarn build:lib || {
    print_error "构建失败，请检查错误信息"
    exit 1
}

# 6. 检查构建输出
print_message "检查构建输出..."
if [ ! -f "dist/index.es.js" ] || [ ! -f "dist/index.umd.js" ] || [ ! -f "dist/index.d.ts" ]; then
    print_error "构建输出文件不完整"
    exit 1
fi

# 7. 更新版本号
print_message "更新版本号 ($VERSION_TYPE)..."
npm version $VERSION_TYPE --no-git-tag-version

# 获取新版本号
NEW_VERSION=$(node -p "require('./package.json').version")
print_message "新版本号: $NEW_VERSION"

# 8. 提交更改
print_message "提交更改..."
git add .
git commit -m "chore: release v$NEW_VERSION"

# 9. 创建标签
print_message "创建 Git 标签..."
git tag "v$NEW_VERSION"

# 10. 推送到远程仓库
print_message "推送到远程仓库..."
git push origin main
git push origin "v$NEW_VERSION"

# 11. 发布到 NPM
print_message "发布到 NPM..."
npm publish

print_message "发布完成！"
print_message "版本: v$NEW_VERSION"
print_message "NPM 包: https://www.npmjs.com/package/vue3-antd-dynamic-form"

# 12. 更新 CHANGELOG
print_warning "请记得更新 CHANGELOG.md 文件，记录本次发布的变更内容" 